package cn.itcast.erp.controller;

import cn.itcast.erp.annotation.CheckPower;
import cn.itcast.erp.entity.Goods;
import cn.itcast.erp.entity.utils.AjaxResult;
import cn.itcast.erp.service.GoodsService;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Resource
    private GoodsService goodsService;

    @CheckPower("商品")
    @RequestMapping("/insert")
    public AjaxResult insertGoods(@Validated Goods goods){
        AjaxResult ar = new AjaxResult();

        this.goodsService.insertGoods(goods);
        ar.setMsg("添加成功");
        return ar;
    }

    @CheckPower("商品")
    @RequestMapping("/delete")
    public AjaxResult deleteGoods(Long uuid){
        AjaxResult ar = new AjaxResult();
        int i = goodsService.deleteGoodsByUuId(uuid);
        if (i>0){
            ar.setMsg("删除成功");
        }else {
            ar.setMsg("删除失败");
        }
        return ar;
    }

    @CheckPower("商品")
    @RequestMapping("/update")
    public AjaxResult updateGoods(@Validated Goods goods){
        AjaxResult ar = new AjaxResult();
        this.goodsService.updateGoods(goods);
        ar.setMsg("修改成功");
        return ar;

    }


    @CheckPower("商品")
    @RequestMapping("/find")
    public AjaxResult findGoods(Goods goods){
        return this.goodsService.findGoods(goods);
    }




    //不分页
    @CheckPower("商品")
    @RequestMapping("/findAll")
    public List<Goods> findAllGoods(){
        return this.goodsService.findAllGoods();
    }


    //查询商品By id
    @CheckPower("商品")
    @RequestMapping("/findById")
    public Goods findGoodsById(Long uuid){
        return this.goodsService.findGoodsById (uuid);
    }


    //导出Excel
    @CheckPower("商品")
    @RequestMapping("/export")
    public void getAllGoodsEx(HttpServletResponse response){
        try {
            response.reset();
            response.setContentType("application/msexcel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("商品信息.xls", "UTF-8"));
            InputStream inputStream = goodsService.getAllGoodsEx();
            IOUtils.copy(inputStream,response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
